package com.aau.edu.aio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
//服务端代码
public class Server {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;//创建服务器套接字对象
        Socket socket = null;//创建套接字对象
        BufferedReader in = null;//创建字符流读取包装类对象

        try {
            serverSocket = new ServerSocket(8888);//使用构造方法绑定服务器端口号
            System.out.println("----------Listening------------");
            socket = serverSocket.accept();//等待客户端连接，并准备接收（阻塞方法）
            System.out.println("----------Accept---------------");
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //初始化字符输入流，让其和Socket对象产生关联，实现从socket读取字节流再转为字符流
            String recvStr = in.readLine();//字符输入流读取一行
            System.out.println(recvStr);
            if (null != serverSocket)
                serverSocket.close();//关闭ServerSocket
            if (null != socket)
                socket.close();//关闭Socket
            if (null != in)
                in.close();//关闭字符输入流
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
